package com.borrowed.book.config.shiro;

import com.borrowed.book.user.domain.SUser;
import com.borrowed.book.user.exception.UserNotExistException;
import com.borrowed.book.user.service.SUserService;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;

/**
 * 登录认证、授权最终都是交给realm实现
 * @author jinbin
 */
public class UserRealm extends AuthorizingRealm {
    private static Logger log = Logger.getLogger(com.borrowed.book.config.shiro.UserRealm.class.getClass());

    @Autowired
    private SUserService userService;

    /**
     * 链接权限，先空着，等后面需要再补充
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        return authorizationInfo;
    }

    /**
     * 登录认证实现
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken=(UsernamePasswordToken)token;
        String username=upToken.getUsername();
        String password="";
        if(upToken.getPassword()!=null) {
            password=new String(upToken.getPassword());
        }
        SUser userinfo=null;
        try {
             userinfo=userService.selectUserByLoginName(username,password);
        }catch (UserNotExistException e){
            throw new UnknownAccountException(e.getMessage(), e);
        }catch (Exception e){
            log.error("对用户["+username+"]进行登录验证，验证未通过");
            throw new AuthenticationException(e.getMessage(),e);
        }


        SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(userinfo,password,getName());
        return authenticationInfo;
    }


}
